package cn.com.jslh.boarpro.main.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimAdapterEx;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.base.mvp.BaseListPresenter;
import cn.com.jslh.boarpro.base.mvp.BaseListView;
import cn.com.jslh.boarpro.main.MainDetilActivity;
import cn.com.jslh.boarpro.main.entity.LineEntity;
import cn.com.jslh.boarpro.main.model.MainModelImpl;
import cn.com.jslh.boarpro.main.view.NewsWarnActivity;
import cn.com.jslh.boarpro.main.view.view.MainView;
import cn.com.jslh.boarpro.tables.ModelTable;
import cn.com.jslh.boarpro.tables.StriplineTable;
import cn.com.jslh.boarpro.util.DownLoadBaseDataUtil;
import cn.com.jslh.boarpro.util.ModuleUtil;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.database.DataBaseUtil;
import cn.com.jslh.boarpro.util.spinnerdialog.OptionsWindowHelper;
import cn.jeesoft.widget.pickerview.CharacterPickerWindow;
import cn.jeesoft.widget.pickerview.OnOptionChangedListener;

/**
 * 作者：周洲 on 2017/7/12 16:09
 * <p>
 * 邮箱：double0zhou@126.com
 */

public class MainPresenterImpl extends BaseListPresenter {
    private SlimAdapterEx adapter;
    private List<LineEntity> lines=new ArrayList<>();
    private LinkedHashMap<String,List<String>> map=new LinkedHashMap();
    private String orgName,lineName;
    private String data="";



    public MainPresenterImpl(Context context, BaseListView baseListView) {
        super(context, baseListView, new MainModelImpl(context));
    }

    @Override
    public void upDatas(String... param) {
        adapter.updateData(baseListModel.getDatas()).notifyDataSetChanged();
        ((MainView) baseListView).setTitle(SPUtils.getInstance().getString(BaseApplication.FORGNAME) + "（" + SPUtils.getInstance().getString(BaseApplication.FLINENAME) + "）");
    }

    @Override
    public void setUI(RecyclerView recyclerView, String... param) {
        adapter = SlimAdapter.create(SlimAdapterEx.class)
                .enableDiff()
                .registerDefault(R.layout.main_gridlist_item, new SlimInjector<ModelTable>() {
                    @Override
                    public void onInject(final ModelTable modelTable, final IViewInjector injector) {
                        injector.text(R.id.title, modelTable.getFFUNNAME())
                                .text(R.id.tv_warn,SPUtils.getInstance().getString(BaseApplication.FCOUNT))
                                .with(R.id.tv_warn, new IViewInjector.Action() {
                                    @Override
                                    public void action(View view) {
                                        if(modelTable.getFFUNNAME().equals("预警提醒")&&!SPUtils.getInstance().getString(BaseApplication.FCOUNT).equals("0")){
                                            view.setVisibility(View.VISIBLE);
                                        }else {
                                            view.setVisibility(View.GONE);
                                        }
                                    }
                                })



                                .with(R.id.icon, new IViewInjector.Action() {
                                    @Override
                                    public void action(View view) {
//                                        GlideApp.with(this).load("http://goo.gl/gEgYUd").into(view);
                                        Glide.with(context).load(modelTable.getFICON()).placeholder(R.mipmap.pig128).into((ImageView) view);
                                    }
                                })

                                .clicked(R.id.icon, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
//                                        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "rotationY", 0.0F, 360.0F);
//                                        objectAnimator.setInterpolator(new LinearOutSlowInInterpolator());
//                                        objectAnimator.setDuration(500);
//                                        objectAnimator.start();
                                        if(modelTable.getFFUNNAME().equals("预警提醒")){
                                            Intent intent=new Intent(context, NewsWarnActivity.class);
                                            context.startActivity(intent);
                                        }else {
                                            goDetailActivity(modelTable.getFFUNNAME());
                                        }

                                    }
                                })
                                .clicked(R.id.item_Layout, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
//                                        ActivityUtils.startActivity((Activity)context, MainDetilActivity.class);
                                        if(modelTable.getFFUNNAME().equals("预警提醒")){
                                            Intent intent=new Intent(context, NewsWarnActivity.class);
                                            context.startActivity(intent);
                                        }else {
                                            goDetailActivity(modelTable.getFFUNNAME());
                                        }
                                    }
                                });
                    }
                })

                .attachTo(recyclerView);
    }

    public void goDetailActivity(final String name) {
        List<ModuleUtil> modules = ModuleUtil.initModules();
        for (int i = 0; i < modules.size(); i++) {
            final ModuleUtil module = modules.get(i);
            if (module.getModuleName().equals(name)) {
                final List<ModuleUtil> menus = new ArrayList<>();
                for (int i1 = 0; i1 < modules.size(); i1++) {
                    ModuleUtil module1 = modules.get(i1);
                    if (module1.getModuleName().equals(name)) {
                        menus.add(module1);
                    }
                }
                if (menus.size() == 1) {
                    MainDetilActivity.moduleUtil = module;
                    ActivityUtils.startActivity((Activity) context, MainDetilActivity.class);
                } else {
                    String[] menuStrs = new String[menus.size()];
                    for (int i1 = 0; i1 < menus.size(); i1++) {
                        menuStrs[i1] = menus.get(i1).getMenuName();
                    }
                    new AlertDialog.Builder(context)
                            .setItems(menuStrs, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    SearchPresenterImpl.SearchType = menus.get(i).getSearchType();
                                    MainDetilActivity.moduleUtil = menus.get(i);
                                    ActivityUtils.startActivity((Activity) context, MainDetilActivity.class);
                                }
                            })
                            .setTitle("选择子功能")
                            .show();
                }
                return;
            }
        }
        Toast.makeText(context, "当前功能正在开发中....", Toast.LENGTH_SHORT).show();
    }

    /**
     * 切换生产条线
     */
    public void setStripline(final View view) {
        new WebService.Builder(context,"exportUserToOrg","WSZpigBaseDataFacade")
                .addProperty("userID",SPUtils.getInstance().getString(BaseApplication.FUSERID))
                .success(new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        Log.d("打印s",s+"zxx");
                        LineEntity entity=JSON.parseObject(s,LineEntity.class);
                        lines= entity.getData();
                        for(int i=0;i<lines.size();i++){
                            List<LineEntity> line=lines.get(i).getLines();
                            List<String> list=new ArrayList<>();
                            for(int j=0;j<line.size();j++){
                                list.add(line.get(j).getLineName());
                            }
                            map.put(lines.get(i).getOrgName(),list);
                        }

                        final OptionsWindowHelper help=new  OptionsWindowHelper((Activity) context,map);
                        final CharacterPickerWindow window =help.builder(new OptionsWindowHelper.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int option1, int option2) {
                                LineEntity info=lines.get(option1).getLines().get(option2);
                                orgName=lines.get(option1).getOrgName();
                                lineName=info.getLineName();
                                SPUtils.getInstance().put(BaseApplication.FORGNAME,orgName);
                                SPUtils.getInstance().put(BaseApplication.FLINEID, info.getLineID());
                                SPUtils.getInstance().put(BaseApplication.FLINENAME, info.getLineName());
                                Log.d("猪场生产线",SPUtils.getInstance().getString(BaseApplication.FLINENAME));
                                ((MainView) baseListView).setTitle(SPUtils.getInstance().getString(BaseApplication.FORGNAME) + "（" + SPUtils.getInstance().getString(BaseApplication.FLINENAME) + "）");
                                getJbData();

                            }
                        });


                        window.showAtLocation(view, Gravity.CENTER,0,0);
                        help.setBackgroundAlpha((Activity)context,0.3f);
                        help.setCurrentPositions(window, orgName, lineName);


                        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                window.dismiss();
                                help.setBackgroundAlpha((Activity)context,1.0f);
                            }
                        });

                    }
                })
                .post();

//        new AlertDialog.Builder(context)
//                .setTitle("请选择条线")
//                .setItems(items, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        StriplineTable striplineTable = (StriplineTable) datas.get(i);
//                        SPUtils.getInstance().put(BaseApplication.FLINEID, striplineTable.getFID());
//                        SPUtils.getInstance().put(BaseApplication.FLINENAME, striplineTable.getFNAME());
//                        ((MainView) baseListView).setTitle(SPUtils.getInstance().getString(BaseApplication.FORGNAME) + "（" + striplineTable.getFNAME() + "）");
//                        Toast.makeText(context, "切换到：" + striplineTable.getFNAME(), Toast.LENGTH_SHORT).show();
//                    }
//                }).show();
    }

    /**
     * 在此下载最新周号
     */
    public void initBaseData() {
        DownLoadBaseDataUtil.downLoadAllData(context);
    }


    public void loginOut(WebService.NetSuccessListener netSuccessListener){
        ((MainModelImpl)baseListModel).loginOut(netSuccessListener);
    }

    public void getJbData(){
        new WebService.Builder(context,"JiaoBiaoCount","WSPigWarnFacade")
                .addProperty("lineID",SPUtils.getInstance().getString(BaseApplication.FLINEID))
                .success(new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        Log.d("角标",s+"zxx");
                        JSONObject jsonObject=new JSONObject(s);
                        data=String.valueOf(jsonObject.getInt("data"));
                        SPUtils.getInstance().put(BaseApplication.FCOUNT,data);
                        Log.d("角标数量",data+"zxx");
                        adapter.notifyDataSetChanged();
                    }
                })
                .post();
    }
}
